package com.k8sops.backend.service.impl;

import com.k8sops.backend.config.DockerRegistryConfig;
import com.k8sops.backend.service.DockerRegistryService;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1ObjectMeta;
import io.kubernetes.client.openapi.models.V1Secret;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * Docker镜像仓库服务实现类
 */
@Service
@Slf4j
public class DockerRegistryServiceImpl implements DockerRegistryService {

    @Resource
    private DockerRegistryConfig dockerRegistryConfig;

    @Resource
    private CoreV1Api coreV1Api;

    @Override
    public String buildImageUrl(Map<String, Object> imageConfig) {
        if (imageConfig == null) {
            return null;
        }

        // 从YAML配置中获取镜像信息
        String registry = (String) imageConfig.get("registry");
        String registryNamespace = (String) imageConfig.get("registryNamespace");
        String repository = (String) imageConfig.get("repository");
        String tag = (String) imageConfig.get("tag");

        // 验证必要的字段
        if (registry == null || repository == null || tag == null) {
            log.warn("镜像配置信息不完整: registry={}, repository={}, tag={}", registry, repository, tag);
            return null;
        }

        // 构建完整的镜像URL
        StringBuilder imageUrl = new StringBuilder();
        imageUrl.append(registry);
        imageUrl.append("/");
        
        if (registryNamespace != null && !registryNamespace.isEmpty()) {
            imageUrl.append(registryNamespace);
            imageUrl.append("/");
        }
        
        imageUrl.append(repository);
        imageUrl.append(":");
        imageUrl.append(tag);

        log.info("构建的镜像URL: {}", imageUrl);
        return imageUrl.toString();
    }

    @Override
    public boolean createImagePullSecret(String namespace, String secretName) {
        try {
            // 获取阿里云Docker仓库配置
            DockerRegistryConfig.RegistryConfig aliyunConfig = dockerRegistryConfig.getAliyunRegistry();
            if (aliyunConfig == null) {
                log.error("阿里云Docker仓库配置不存在");
                return false;
            }

            // 创建Docker配置JSON
            String dockerConfigJson = createDockerConfigJson(aliyunConfig);
            if (dockerConfigJson == null) {
                return false;
            }

            // 创建Secret
            V1Secret secret = new V1Secret()
                    .apiVersion("v1")
                    .kind("Secret")
                    .metadata(new V1ObjectMeta().name(secretName).namespace(namespace))
                    .type("kubernetes.io/dockerconfigjson");

            // 添加Docker配置数据
            Map<String, byte[]> data = new HashMap<>();
            data.put(".dockerconfigjson", dockerConfigJson.getBytes(StandardCharsets.UTF_8));
            secret.setData(data);

            // 创建Secret
            coreV1Api.createNamespacedSecret(namespace, secret, null, null, null, null);
            log.info("成功创建镜像拉取Secret: {}/{}", namespace, secretName);
            return true;
        } catch (ApiException e) {
            log.error("创建镜像拉取Secret失败: {}", e.getResponseBody(), e);
            return false;
        } catch (Exception e) {
            log.error("创建镜像拉取Secret时发生异常", e);
            return false;
        }
    }

    /**
     * 创建Docker配置JSON
     *
     * @param registryConfig Docker仓库配置
     * @return Docker配置JSON
     */
    private String createDockerConfigJson(DockerRegistryConfig.RegistryConfig registryConfig) {
        try {
            // 构建认证字符串
            String auth = registryConfig.getUsername() + ":" + registryConfig.getPassword();
            String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));

            // 构建Docker配置JSON
            return String.format(
                    "{\"auths\":{\"https://%s\":{\"username\":\"%s\",\"password\":\"%s\",\"email\":\"%s\",\"auth\":\"%s\"}}}",
                    registryConfig.getUrl(),
                    registryConfig.getUsername(),
                    registryConfig.getPassword(),
                    registryConfig.getEmail(),
                    encodedAuth
            );
        } catch (Exception e) {
            log.error("创建Docker配置JSON时发生异常", e);
            return null;
        }
    }
}
